Django documentation

4. Many-to-one relationships

To define a many-to-one relationship, use ForeignKey() .

Model source code

from django.core import meta

class Reporter(meta.Model):
    first_name = meta.CharField(maxlength=30)
    last_name = meta.CharField(maxlength=30)
    email = meta.EmailField()

    def __repr__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Article(meta.Model):
    headline = meta.CharField(maxlength=100)
    pub_date = meta.DateField()
    reporter = meta.ForeignKey(Reporter)

    def __repr__(self):
        return self.headline

API reference

Reporter objects have the following methods:

  • add_article()
  • delete()
  • get_article()
  • get_article_count()
  • get_article_list()
  • save()

Article objects have the following methods:

  • delete()
  • get_next_by_pub_date()
  • get_previous_by_pub_date()
  • get_reporter()
  • save()

Sample API usage

This sample code assumes the above models have been saved in a file examplemodel.py.

>>> from django.models.examplemodel import reporters, articles

# Create a Reporter.
>>> r = reporters.Reporter(first_name='John', last_name='Smith', email='john@example.com')
>>> r.save()

# Create an Article.
>>> from datetime import datetime
>>> a = articles.Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter=r)
>>> a.save()

>>> a.reporter_id
1

>>> a.get_reporter()
John Smith

# Article objects have access to their related Reporter objects.
>>> r = a.get_reporter()
>>> r.first_name, r.last_name
('John', 'Smith')

# Create an Article via the Reporter object.
>>> new_article = r.add_article(headline="John's second story", pub_date=datetime(2005, 7, 29))
>>> new_article
John's second story
>>> new_article.reporter_id
1

# Reporter objects have access to their related Article objects.
>>> r.get_article_list(order_by=['pub_date'])
[This is a test, John's second story]

>>> r.get_article(headline__startswith='This')
This is a test

>>> r.get_article_count()
2

# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want. There's no limit.
# Find all Articles for any Reporter whose first name is "John".
>>> articles.get_list(reporter__first_name__exact='John', order_by=['pub_date'])
[This is a test, John's second story]

# Find all Articles for the Reporter whose ID is 1.
>>> articles.get_list(reporter__id__exact=1, order_by=['pub_date'])
[This is a test, John's second story]

# Note you need two underscores between "reporter" and "id" -- not one.
>>> articles.get_list(reporter_id__exact=1)
Traceback (most recent call last):
    ...
TypeError: got unexpected keyword argument 'reporter_id__exact'

# "pk" shortcut syntax works in a related context, too.
>>> articles.get_list(reporter__pk=1, order_by=['pub_date'])
[This is a test, John's second story]

# You can also instantiate an Article by passing
# the Reporter's ID instead of a Reporter object.
>>> a3 = articles.Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter_id=r.id)
>>> a3.save()
>>> a3.reporter_id
1
>>> a3.get_reporter()
John Smith

# Similarly, the reporter ID can be a string.
>>> a4 = articles.Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter_id="1")
>>> a4.save()
>>> a4.get_reporter()
John Smith

Comments

cyang August 4, 2005 at 12:19 a.m.

Why not change
>>> a = articles.Article(id=None, headline='This is a test', pub_date=datetime(2005, 7, 27), reporter_id=r.id)
to
>>> a = articles.Article(id=None, headline='This is a test', pub_date=datetime(2005, 7, 27), reporter=r)
.
Which is more intuitive.

armand August 5, 2005 at 6:16 a.m.

Is it possible in this example to retrieve a list of all the
reporters who submitted an article on a specific date?

Something like:
reporters.get_list(article__pub_date__exact=datetime(2005, 8, 5))

Post a comment

Note: Please only use the comments for questions/critcisms/suggestions on the docs; if you experience errors please file a ticket, ask in the IRC channel, or post to the django-users list. Comments will be periodically reviewed, integrated into the documentation proper, and removed.

Your name:

Comment: